<template>
  <div class="login-wel">
    <div class="wel-container" v-if="isShow">
      <img src="../../images/logo.webp" />
      <span>{{ data }}</span>
      <van-circle
        v-model="currentRate"
        size="64px"
        :clockwise="false"
        :text="String(Math.ceil(this.currentRate / 20)) + 's'"
        color="#69c0ff"
   @click.native="closeEvt"
      />
    </div>

    <div class="login-container" v-else>
      <img src="../../images/welLogo.jpg" alt="" />

      <!-- 电话号码输入框 -->
      <div class="input">
        <van-field placeholder="请输入登录手机号" v-model="phone" /><van-icon
          name="clear"
          @click.native="clear"
        />

        <!-- 验证码输入框 -->
        <van-field placeholder="请输验证码" v-model="code" />
        <span class="getCode" @click="getCode">{{msg}}</span>

        <!-- <span class="getCode">获取验证码</span> -->
      </div>
      <!-- 复选框 -->
      <span class="checkbox">
        <van-checkbox v-model="remember">记住电话号码？</van-checkbox>
        <van-checkbox v-model="auto">是否自动登录？</van-checkbox>
      </span>
      <!-- 登录 -->
      <van-button type="primary" block color="#40a9ff" @click="login" :disabled="!canSubmit"
        >登录</van-button
      >
    </div>
  </div>
</template>
<script>
import { loginApi, autoLoginApi, userRoleApi, vdtCodeApi, userInfoApi } from '@/Apis/userApis'
export default {
  name: 'index',
  data () {
    return {
      isShow: true,
      currentRate: 100,
      timer: null,
      value: '',
      phone: '',
      code: '',
      remember: '',
      auto: '',
      msg: '获取验证码',
      autoLogin: 'loading',
      vdtTimer: null,
      data: [
        ' 一切都会过去，只有真理永存',
        '科学是使人的精神变得勇敢的最好途径',

        '因为真理是灿烂的，只要有一个罅隙，就能照亮整个田野',

        '认识真理的主要障碍不是谬误，而是似是而非的真理',

        '那些没有受过未知事物折磨的人，不知道什么是发现的快乐',

        '真理的伟大朋友是时间，她的最大的敌人是偏见，她永恒的伴侣是谦虚'
      ][Math.floor(Math.random() * 6)]
    }
  },
  async created () {
    // 环形进度条的外圈颜色走动********************************************
    this.timer = setInterval(() => {
      this.currentRate -= 1
      if (this.currentRate < 1) {
        clearInterval(this.timer)
        this.isShow = false
      }
    }, 5000 / 100)

    //  判断是否有免登录********************************************
    const autoToken = localStorage.getItem('auto-token')
    if (autoToken) {
      this.$store.commit('common/setToken', autoToken)
      sessionStorage.setItem('token', autoToken)
      // 请求自动登录接口
      const res = await autoLoginApi()
      if (res.code === 200) {
        this.$store.commit('common/setUserInfo', res.data)

        // 请求用户角色信息接口
        const role = await userRoleApi(res.data.role)
        this.$store.commit('common/setUserRole', role.data)
        // 自动登录成功
        this.autoLogin = 'success'
      } else {
        this.autoLogin = 'error'
      }
    } else {
      this.autoLogin = 'error'
    }

    //  判断是否记住号码********************************************
    const phonecache = localStorage.getItem('phone')
    if (phonecache) {
      this.phone = phonecache
      this.remember = true
    }
  },
  computed: {
    canSubmit () {
      return /^1[3-9]{1}[0-9]{9}$/.test(this.phone) && /^[0-9]{4}$/.test(this.code)
    }
  },
  watch: {
    phone (val) {
      this.code = ''
    }
  },
  methods: {
    // 点击倒计时切换到登录页面*******************************************
    closeEvt () {
      if (this.autoLogin === 'loading') {
        return false
      }
      this.toPage()
    },
    toPage () {
      clearInterval(this.timer)
      if (this.autoLogin === 'error') {
        this.isShow = false
      } else {
        this.$router.push('/home')
      }
    },
    // 提交登录*******************************************
    async login () {
      // 登录接口需要传参
      if (!this.canSubmit) return
      // 请求接口
      const Login = await loginApi({
        phone: this.phone,
        vdtCode: this.code

      })

      // 登录失败提示
      if (Login.code !== 200) {
        this.$toast.fail('登录失败，请重试')
        return
      }
      this.$store.commit('common/setToken', Login.data.token)
      sessionStorage.setItem('token', Login.data.token)

      // 请求用户信息
      const userInfo = await userInfoApi(Login.data.id)
      console.log(userInfo, 111)

      this.$store.commit('common/setUserInfo', userInfo.data)

      const userRole = await userRoleApi(userInfo.data.role)
      console.log(userRole, 123)
      this.$store.commit('common/setUserRole', userRole.data)

      if (this.remember) {
        localStorage.setItem('phone', this.phone)
      } else {
        localStorage.removeItem('phone')
      }
      if (this.auto) {
        localStorage.setItem('auto-token', Login.data.token)
      } else {
        localStorage.removeItem('auto-token')
      }

      this.$router.push('/home')
    },
    // 点击叉图标清空手机号输入框
    clear () {
      this.phone = ''
    },
    // 点击获取验证码*******************************************
    async getCode () {
      // 节流
      if (this.msg !== '获取验证码') return
      // 正则手机号，并做提示
      if (!/^1[3-9]{1}[0-9]{9}$/.test(this.phone)) {
        this.$toast({
          message: '请输入正确的手机码',
          position: 'bottom'
        })
        return
      }
      this.msg = '获取中.....'
      // 发送验证码请求
      const res = await vdtCodeApi(this.phone)
      // 请求失败的判断
      if (!res) {
        this.$toast.fail('获取验证码失败，请重新获取')
        this.msg = '重新获取'
      }
      this.$toast.success(`获取验证码\n${res.data.vdtCode}`)

      this.loop(Date.now())
    },
    // 60s倒计时
    loop (st) {
      const passTime = Math.ceil(60 - (Date.now() - st) / 1000)
      this.msg = `重新获取${passTime + 's'}`
      this.vdtTimer = setTimeout(() => {
        if (passTime > 0) {
          this.loop(st)
        } else {
          this.msg = '获取验证码'
          clearTimeout(this.vdtTimer)
        }
      }, 200)
    }
  },
  beforeDestroy () {
    clearTimeout(this.vdtTSimer)
  }
}
</script>
<style lang="less" scoped>
@import "../../style/common.less";
.login-wel {
  .common;
  .wel-container {
    .common;
    padding: 18vh 5vw 0;

    > img {
      width: 60px;
      height: 60px;
      margin: auto;
      display: block;
    }
    span {
      display: block;
      color: @c9;
      font-size: 0.75rem;
      text-align: center;
    }
    .van-circle {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
  .login-container {
    .common;
    padding: 18vh 5vw 0;
    > img {
      width: 60px;
      height: 60px;
      margin: auto;
      display: block;
    }
    .input {
      width: 100%;
      position: relative;
      margin-bottom: 15px;
      .van-field {
        height: 70px;
        background-color: @c1;
        outline: none;
        border: none;

        border-bottom: 1px solid @c5;
        font-size: 0.8rem;
        line-height: 50px;
      }
      .van-icon {
        font-size: 16px;
        color: @c4;
        position: absolute;
        top: 13px;
        right: 10px;
      }
      .getCode {
        position: absolute;
        top: 69%;
        left: 65%;
        height: 100%;
        padding-left: 10px;
        display: block;
        background-color: @c1;
        outline: none;
        border: none;
        border-left: 1px solid @c5;
        font-size: 0.7rem;
        color: #464646;
        height: 35px;

        line-height: 35px;
      }
    }
    .van-button {
      border-radius: 22px;
      height: 46px;
    }
    .checkbox {
      display: block;
        color: @c7;

      font-size: 0.8rem;
      .van-checkbox {
        margin-bottom: 10px;
        color: @c7;

      }
    }
  }
}
</style>
